package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.*;
import com.mbyte.easy.admin.service.*;
import com.mbyte.easy.common.constant.*;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.service.IUserService;
import com.mbyte.easy.util.OssFileUtils;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mbyte.easy.common.constant.StatusConstant.*;

/**
* <p>
* 前端控制器
* </p>
* @author lp
* @since 2019-03-11
*/
@Slf4j
@Controller
@RequestMapping("/admin/draft")
public class DraftController extends BaseController  {

    private String prefix = "admin/draft/";

    @Autowired
    private IDraftService draftService;
    @Autowired
    private ICheckService checkService;
    @Autowired
    private IPptService pptService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAllotService allotService;

    @Autowired
    private IGroupService groupService;
    @Autowired
    private IAudioService audioService;
    @Autowired
    private IDraftLogService draftLogService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;


    /**
    * 查询列表
    *
    * @param model
    * @param pageNo
    * @param pageSize
    * @param draft
    * @return
    */
    @RequestMapping
    public String index(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
         }
        if(!ObjectUtils.isEmpty(draft.getDraftText())) {
            queryWrapper = queryWrapper.like("draft_text",draft.getDraftText());
         }
        if(!ObjectUtils.isEmpty(draft.getDraftNum())) {
            queryWrapper = queryWrapper.like("draft_num",draft.getDraftNum());
         }
        if(!ObjectUtils.isEmpty(draft.getDraftType())) {
            queryWrapper = queryWrapper.like("draft_type",draft.getDraftType());
         }
        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            queryWrapper = queryWrapper.like("submit_time",draft.getSubmitTime());
         }
        if(!ObjectUtils.isEmpty(draft.getUserId())) {
            queryWrapper = queryWrapper.like("user_id",draft.getUserId());
         }
        if(!ObjectUtils.isEmpty(draft.getStatusCode())) {
            queryWrapper = queryWrapper.like("status_code",draft.getStatusCode());
         }
        if(!ObjectUtils.isEmpty(draft.getIsDelete())) {
            queryWrapper = queryWrapper.like("is_delete",draft.getIsDelete());
         }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            queryWrapper = queryWrapper.like("group_id",draft.getGroupId());
         }
        if(!ObjectUtils.isEmpty(draft.getLastOperator())) {
            queryWrapper = queryWrapper.like("last_operator",draft.getLastOperator());
         }
        if(!ObjectUtils.isEmpty(draft.getIsPass())) {
            queryWrapper = queryWrapper.like("is_pass",draft.getIsPass());
         }
        IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
        model.addAttribute("submitTimeSpace", submitTimeSpace);
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix+"list";

    }

    /**
     *@author 孙祺至
     *@date 2019/12/8 20:57
     * 录屏课程负责人PPT管理下的未分配
     */
    @RequestMapping("PPT_unallot_Leader")
    public String index_PPT_unallot(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                    @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                    String submitTimeSpace,
                                    String createTimeSpace,
                                    String updateTimeSpace,
                                    Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftText())) {
            queryWrapper = queryWrapper.like("draft_text",draft.getDraftText());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftNum())) {
            queryWrapper = queryWrapper.like("draft_num",draft.getDraftNum());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftType())) {
            queryWrapper = queryWrapper.like("draft_type",draft.getDraftType());
        }
        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            queryWrapper = queryWrapper.like("submit_time",draft.getSubmitTime());
        }
        if(!ObjectUtils.isEmpty(draft.getUserId())) {
            queryWrapper = queryWrapper.like("user_id",draft.getUserId());
        }
        if(!ObjectUtils.isEmpty(draft.getStatusCode())) {
            queryWrapper = queryWrapper.like("status_code",draft.getStatusCode());
        }
        if(!ObjectUtils.isEmpty(draft.getIsDelete())) {
            queryWrapper = queryWrapper.like("is_delete",draft.getIsDelete());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            queryWrapper = queryWrapper.like("group_id",draft.getGroupId());
        }
        if(!ObjectUtils.isEmpty(draft.getLastOperator())) {
            queryWrapper = queryWrapper.like("last_operator",draft.getLastOperator());
        }
        if(!ObjectUtils.isEmpty(draft.getIsPass())) {
            queryWrapper = queryWrapper.like("is_pass",draft.getIsPass());
        }
        queryWrapper.lambda().eq(Draft::getStatusCode, StatusWriter.STATUS_WRRITE_ARTICLEFINALLEADER_SUCCESS);
        queryWrapper.lambda().eq(Draft::getDraftType, StatusConstant.STATUS_PPT);
        queryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
        PageInfo info = new PageInfo(pageInfo);
//        List<Draft>draftList = info.getList();
//        for(Draft draft1:draftList){
//            if (draft1.getUserId()!=null){
//                draft1.setWriterName(userService.selectByPrimaryKey(draft1.getUserId()).getUsername());
//            }
//            int length=  StringUtils.isNoneBlank(draft1.getDraftText()) ? draft1.getDraftText().length() : 0;
//            if(length>10){
//                draft1.setSubText(draft1.getDraftText().substring(0,10)+"...") ;
//            }else {
//                draft1.setSubText( draft1.getDraftText());
//            }
//        }
        Map<Long,String> longStringMap=new HashMap<>();
        List<Draft> draftList=draftService.list(queryWrapper);
        for (Draft draft1 : draftList) {
            if (draft1.getUserId()!=null){
                SysUser sysUser = userService.selectByPrimaryKey(draft1.getUserId());
                if (sysUser!=null){
                    log.info("=========sysuser===="+sysUser.getUsername());
                    longStringMap.put(draft1.getId(),sysUser.getUsername());
                    log.info("======draft1.getWritername==="+draft.getWriterName());
                }
            }
        }
        model.addAttribute("writerName",longStringMap);
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo",info);
        return prefix+"pptunAllot";
    }

    /**
     *@author 孙祺至
     *@date 2019/12/8 20:57
     * 音视频校对人PPT管理下的已分配
     */
    @RequestMapping("PPT_allot")
    public String index_PPT_allot(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                  @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                  String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();

        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
            groupQueryWrapper.lambda().like(Group::getName,draft.getGroupId());
            List<Group> list = groupService.list(groupQueryWrapper);
            log.info("==========draftName==========="+draft.getGroupId());
            if (list.size()!=0){
                log.info("===============进入=========="+list);
                queryWrapper = queryWrapper.in("td.group_id",list.stream().map(Group::getGroupId).collect(Collectors.toList()));
            }else {
                queryWrapper.eq("td.group_id","0");
            }
        }
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
                queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }

//        Map<Long,String> map = new HashMap<>();
        Long idByUserName = draftService.getIdByUserName(Utility.getCurrentUsername());
        List<Allot> allot=draftService.getDraftByUserId(idByUserName);
        if (allot.size()!=0){
            queryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
            queryWrapper.lambda().eq(Draft::getDraftType, StatusConstant.STATUS_PPT);
            queryWrapper.in("td.id",allot.stream().map(Allot::getDraftId).collect(Collectors.toList()));
//            List<Long> draftid=new ArrayList<>();
//            List<Draft> draftList=draftService.list(queryWrapper);
//            Map<Long,String> longStringMap=new HashMap<>();
//            for (Draft draft1 : draftList) {
//                draftid.add(draft1.getId());
//                if (draft1.getUserId()!=null){
//                    SysUser sysUser = userService.selectByPrimaryKey(draft1.getUserId());
//
//                    if (sysUser!=null){
//                        log.info("=========sysuser===="+sysUser.getUsername());
//                        longStringMap.put(draft1.getId(),sysUser.getUsername());
//                        draft.setWriterName(sysUser.getUsername());
//                        log.info("======draft1.getWritername==="+draft.getWriterName());
//                    }
//                }
//            }
//            List<Draft> draftList=draftService.list(queryWrapper);
//            model.addAttribute("writerName",longStringMap);
//            QueryWrapper<Allot>allotQueryWrapper=new QueryWrapper<>();
//            allotQueryWrapper.lambda().eq(Allot::getAllotId,idByUserName).eq(Allot::getStatusCode,StatusPPTAudio.STATUS_PPT_FUNCTIONARY_DISTRIBUTION)
//                    .groupBy(Allot::getDraftId);
//            if(draftid.size()!=0){
//                allotQueryWrapper=allotQueryWrapper.in("draft_id",draftid);
//                List<Allot> draftByUserId = allotService.list(allotQueryWrapper);
//                for (int i = 0; i < draftByUserId.size(); i++) {
//                        String userNameByUserId = draftService.getNameByUserId(draftByUserId.get(i).getAllotnoId());
//                        map.put(draftByUserId.get(i).getDraftId(),userNameByUserId);
//                }
//            }
            //组名
//            List<Draft> list1 = draftService.list(queryWrapper);
//            Map<String,String> groupMap=new HashMap<>();
//            for (int i = 0; i < draftList.size(); i++) {
//                String name = groupService.getNameByGroupId(draftList.get(i).getGroupId());
//                groupMap.put(draftList.get(i).getGroupId(),name);
//            }
            IPage<Draft> pageInfo = draftService.listPage(page, queryWrapper,idByUserName);
//            model.addAttribute("groupMap", groupMap);
//            model.addAttribute("map",map);
//            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptAllot";
        }else {
            queryWrapper.lambda().eq(Draft::getDraftType,"-1");
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptAllot";
        }
    }
    /**
     *@author 孙祺至
     *@date 2019/12/10 9:50
     * 视频校对人未分配PPt稿件
     */
    @RequestMapping("PPT_reader_unallot")
    public String index_PPT_reader_unallot(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftText())) {
            queryWrapper = queryWrapper.like("draft_text",draft.getDraftText());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftNum())) {
            queryWrapper = queryWrapper.like("draft_num",draft.getDraftNum());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftType())) {
            queryWrapper = queryWrapper.like("draft_type",draft.getDraftType());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
            groupQueryWrapper.lambda().like(Group::getName,draft.getGroupId());
            List<Group> list = groupService.list(groupQueryWrapper);
            if (list.size()!=0){
                queryWrapper = queryWrapper.in("td.group_id",list.stream().map(Group::getGroupId).collect(Collectors.toList()));
            }else {
                queryWrapper.eq("td.group_id","0");
            }
        }

        queryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        SysUser userIdByUserName = draftService.getUserIdByUserName(Utility.getCurrentUsername());

        List<Allot> draftByUserId = draftService.getDraftByAllotnoId(userIdByUserName.getId());
        Map<Long,String> longStringMap=new HashMap<>();
        if (draftByUserId.size()!=0){
//            log.info("==================allot======"+draftByUserId);
            queryWrapper.in("td.id",draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.eq("td.status_code", StatusPPTAudio.STATUS_PPT_FUNCTIONARY_DISTRIBUTION);
//            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
//            PageInfo info = new PageInfo(pageInfo);
//            List<Draft>draftList = info.getList();
//            for(Draft draft1:draftList){
//                if (draft1.getUserId()!=null){
//                    longStringMap.put(draft1.getId(),userService.selectByPrimaryKey(draft1.getUserId()).getUsername());
//                }
//                int length=  StringUtils.isNoneBlank(draft1.getDraftText()) ? draft1.getDraftText().length() : 0;
//                if(length>10){
//                    draft1.setSubText(draft1.getDraftText().substring(0,10)+"...") ;
//                }else {
//                    draft1.setSubText( draft1.getDraftText());
//                }
//            }

            //组名
//            List<Draft> list1 = draftService.list(queryWrapper);
//            Map<String,String> groupMap=new HashMap<>();
//            for (int i = 0; i < list1.size(); i++) {
//                String name = groupService.getNameByGroupId(list1.get(i).getGroupId());
//                groupMap.put(list1.get(i).getGroupId(),name);
//            }
//            log.info("============list1========="+list1);
//            log.info("============mao========="+groupMap);
//            model.addAttribute("groupMap", groupMap);
//            model.addAttribute("writerName",longStringMap);

            IPage<Draft> pageInfo = draftService.listPage(page, queryWrapper,userIdByUserName.getId());
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptReaderunAllot";
        }else {
            queryWrapper.lambda().eq(Draft::getDraftType,"-1");
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptReaderunAllot";
        }
    }
    /**
     *@author 孙祺至
     *@date 2019/12/10 9:50
     * 视频校对人分配PPt稿件
     */
    @RequestMapping("PPT_reader_allot")
    public String index_PPT_reader_allot(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("td.draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
            groupQueryWrapper.lambda().like(Group::getName,draft.getGroupId());
            List<Group> list = groupService.list(groupQueryWrapper);
            if (list.size()!=0){
                queryWrapper = queryWrapper.in("td.group_id",list.stream().map(Group::getGroupId).collect(Collectors.toList()));
            }else {
                queryWrapper.eq("td.group_id","0");
            }
        }
        Long idByUserName = draftService.getIdByUserName(Utility.getCurrentUsername());
        queryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        QueryWrapper<Allot>allotQueryWrapper=new QueryWrapper<>();
        allotQueryWrapper.lambda().eq(Allot::getAllotId,idByUserName).eq(Allot::getStatusCode,StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION);
        List<Allot> draftByUserId = allotService.list(allotQueryWrapper);
//        List<Allot> draftByUserId = draftService.getDraftByUserId(idByUserName);


//        QueryWrapper<Allot> allot = new QueryWrapper<>();
//        allot.lambda().eq(Allot::getAllotId,idByUserName)
//                .eq(Allot::getStatusCode, StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION);
//        List<Allot> list = allotService.list(allot);
//
//            Map<Long,String> map = new HashMap<>();
//            for(int i=0;i<draftByUserId.size();i++){
//                String userNameByUserId = draftService.getNameByUserId(draftByUserId.get(i).getAllotnoId());
//                map.put(draftByUserId.get(i).getDraftId(),userNameByUserId);
//            }
//            model.addAttribute("map",map);


        if (draftByUserId.size()!=0){
            log.info("==================Vallot======"+draftByUserId);
            queryWrapper.in("td.id",draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
//            queryWrapper.lambda().eq(Date::);
//            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
//            PageInfo info = new PageInfo(pageInfo);
//            List<Draft>draftList = info.getList();
//            for(Draft draft1:draftList){
//                if (draft1.getUserId()!=null){
//                    draft1.setWriterName(userService.selectByPrimaryKey(draft1.getUserId()).getUsername());
//                }
//                int length=  StringUtils.isNoneBlank(draft1.getDraftText()) ? draft1.getDraftText().length() : 0;
//                if(length>10){
//                    draft1.setSubText(draft1.getDraftText().substring(0,10)+"...") ;
//                }else {
//                    draft1.setSubText( draft1.getDraftText());
//                }
//            }
//            Map<Long,String> longStringMap=new HashMap<>();
//            PageInfo info = new PageInfo(pageInfo);
//            List<Draft>draftList = info.getList();
//            for(Draft draft1:draftList){
//                if (draft1.getUserId()!=null){
//                    longStringMap.put(draft1.getId(),userService.selectByPrimaryKey(draft1.getUserId()).getUsername());
//                }
//            }
//            model.addAttribute("writerName",longStringMap);
//            //组名
//            List<Draft> list1 = draftService.list(queryWrapper);
//            Map<String,String> groupMap=new HashMap<>();
//            for (int i = 0; i < list1.size(); i++) {
//                String name = groupService.getNameByGroupId(list1.get(i).getGroupId());
//                groupMap.put(list1.get(i).getGroupId(),name);
//            }
//            log.info("============list1========="+list1);
//            log.info("============mao========="+groupMap);
//            model.addAttribute("groupMap", groupMap);
            IPage<Draft> pageInfo = draftService.listPage(page, queryWrapper,idByUserName);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptReaderAllot";
        }else{
            queryWrapper.lambda().eq(Draft::getDraftType,"-1");
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptReaderAllot";
        }
    }
    /**
     *@author 孙祺至
     *@date 2019/12/10 9:50
     * PPT录屏制作人未制作PPt稿件
     */
    @RequestMapping("article_to_ppt_unmake")
    public String article_to_ppt_unmake(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                        String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
            groupQueryWrapper.lambda().like(Group::getName,draft.getGroupId());
            List<Group> list = groupService.list(groupQueryWrapper);
            if (list.size()!=0){
                queryWrapper = queryWrapper.in("td.group_id",list.stream().map(Group::getGroupId).collect(Collectors.toList()));
            }else {
                queryWrapper.eq("td.group_id","0");
            }
        }
        queryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        SysUser userIdByUserName = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        log.info("当前登录人的id、===============>{}",userIdByUserName.getId());
        List<Allot> draftByUserId = draftService.getDraftByAllotnoId(userIdByUserName.getId());
        log.info("==========所有的被分配的稿件id=======>{}",draftByUserId);
        if (draftByUserId.size()!=0){
            queryWrapper.in("td.id",draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.eq("td.status_code", StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION).eq("td.draft_type", STATUS_PPT);
//            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
//            PageInfo info = new PageInfo(pageInfo);
//            List<Draft>draftList = info.getList();
//            for(Draft draft1:draftList){
//                if (draft1.getUserId()!=null){
//                    draft1.setWriterName(userService.selectByPrimaryKey(draft1.getUserId()).getUsername());
//                }
//                int length=  StringUtils.isNoneBlank(draft1.getDraftText()) ? draft1.getDraftText().length() : 0;
//                if(length>9){
//                    draft1.setSubText(draft1.getDraftText().substring(0,10)+"...") ;
//                }else {
//                    draft1.setSubText( draft1.getDraftText());
//                }
//            }

//            //组名
//            List<Draft> list1 = draftService.list(queryWrapper);
//            Map<String,String> groupMap=new HashMap<>();
//            for (int i = 0; i < list1.size(); i++) {
//                String name = groupService.getNameByGroupId(list1.get(i).getGroupId());
//                groupMap.put(list1.get(i).getGroupId(),name);
//            }
//            log.info("============list1========="+list1);
//            log.info("============mao========="+groupMap);
//            model.addAttribute("groupMap", groupMap);
            IPage<Draft> pageInfo = draftService.listPage(page, queryWrapper,userIdByUserName.getId());
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptUnmake";
        }else {
            queryWrapper.lambda().eq(Draft::getDraftType,"-1");
             IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"pptUnmake";
        }
    }



    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("addBefore")
    public String addBefore(){
        return prefix+"add";
    }
    /**
    * 添加
    * @param draft
    * @return
    */
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(Draft draft){
        return toAjax(draftService.save(draft));
    }
    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("editBefore/{id}")
    public String editBefore(Model model,@PathVariable("id")Long id){
        model.addAttribute("draft",draftService.getById(id));
        return prefix+"edit";
    }
    /**
    * 添加
    * @param draft
    * @return
    */
    @PostMapping("edit")
    @ResponseBody
    public AjaxResult edit(Draft draft){
        return toAjax(draftService.updateById(draft));
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @GetMapping("delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("id") Long id){
        return toAjax(draftService.removeById(id));
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @PostMapping("deleteAll")
    @ResponseBody
    public AjaxResult deleteAll(@RequestBody List<Long> ids){
        return toAjax(draftService.removeByIds(ids));
    }



    /**
     *@author 孙祺至
     *@date 2019/12/8 22:01
     * 音视频校对组长
     * 跳转unallot.html
     *
     * @update 2020年2月3日15:13:11
     * 录屏课程负责人
     * @author 孙祺至
     * 分配PPT稿件
     */
    @RequestMapping("PPT_to_unallot")
    public String PPT_to_unallot(Model model,String ids){
        SysUser sysUser=draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Long> childrenId=draftService.getChildrenIdByParentId(sysUser.getId());
        log.info("==============登录人id==========="+sysUser.getId());
        log.info("===============下属列表==============="+childrenId);
        Map<Integer,String> map=new HashMap<>();
        for (int i = 0; i < childrenId.size(); i++) {
            //======================肖
            SysUser children = userService.selectByPrimaryKey(childrenId.get(i));
            log.info("========第"+i+"次的循环，下属中的id为"+childrenId.get(i)+"的user为"+children.getId());
            List<com.mbyte.easy.security.entity.SysRole> childrenRoles = children.getRoles();
            log.info("=================角色id对应的role是======="+childrenRoles);
            for (com.mbyte.easy.security.entity.SysRole childrenRole : childrenRoles) {
                if (SysRole.PPT_BROKER.equals(childrenRole.getId())){
                    map.put(i,draftService.getUserNameByUserId(childrenId.get(i)).getUsername());
                }
            }
            //======================
        }
        log.info("============map里有什么=========="+map);
        log.info("=============ids=============="+ids);
        model.addAttribute("username",map);
        model.addAttribute("ids",ids);

        return prefix+"unallot";
    }

    /**
     *@author 孙祺至
     *@date 2019/12/8 21:28
     * 音视频校对组长
     * ppt未分配页面按钮：分配
     * 实现分配功能
     */
    @PostMapping("PPT_unallot")
    @ResponseBody
    public AjaxResult  PPT_unallot(String status,Model model,String ids,String name) {
        log.info("==============ids===========>{}",ids);
        //稿件ids
        //插入group表
        Group group=new Group();
        String UUid=Utility.getUUID();
        group.setGroupId(UUid);
        name = Utility.getGroupName(name);
        if(groupService.existGroupName(name)){
            return AjaxResult.error("组名【"+name+"】今日已存在！");
        }
        String id=ids.substring(0,ids.length()-1);
        String[] idss=id.split(",");
        List<Long> draftid=new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }
        SysUser sysUser = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        //被分配人id
        SysUser sysUser1 = draftService.getUserIdByUserName(status);

        for (int i = 0; i < draftid.size(); i++) {
            //更新稿件
            Draft draft = new Draft();
            draft.setId(draftid.get(i));
            draft.setStatusCode(StatusPPTAudio.STATUS_PPT_FUNCTIONARY_DISTRIBUTION);//1030
            draft.setGroupId(UUid);
            draft.setUpdateTime(LocalDateTime.now());
            draft.setLastOperator(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
            draftService.updateById(draft);

            //插入分配表
            Allot allot=new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(StatusPPTAudio.STATUS_PPT_FUNCTIONARY_DISTRIBUTION);//1030
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);
        }

        group.setName(name);
        group.setUserId(sysUser1.getId());
        draftService.insertToGroup(group);

        //操作日志
        for (int i = 0; i < draftid.size(); i++) {
            applicationEventPublisher.publishEvent(new DraftLog()
                    .setGroupId(UUid)
                    .setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setCreateTime(LocalDateTime.now())
                    .setUserId(Utility.getSysUser().getId())
                    .setDraftId(draftid.get(i))
                    .setPrimaryState(STATUS_DRAFT_AUDIO_UNALLOT)
                    .setAfterState(StatusPPTAudio.STATUS_PPT_FUNCTIONARY_DISTRIBUTION));
        }

        return AjaxResult.success();
    }

    /**
     *@author 孙祺至
     *@date 2019/12/8 22:01
     * 视频校对人
     * 分配
     * 跳转unallot.html
     */
    @GetMapping("PPT_to_reader_unallot_s")
    public String PPT_to_reader_unallot_s(Model model,String ids){
        SysUser sysUser=draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Long> childrenId=draftService.getChildrenIdByParentId(sysUser.getId());
        Map<Integer,String> map=new HashMap<>();
        for (int i = 0; i < childrenId.size(); i++) {
            map.put(i,draftService.getUserNameByUserId(childrenId.get(i)).getUsername());
        }
        model.addAttribute("username",map);
        model.addAttribute("ids",ids);

        return prefix+"Readerunallot";
    }

    /**
     *@author 孙祺至
     *@date 2019/12/8 21:28
     * 视频校对人
     * ppt未分配页面按钮：分配
     * 实现分配功能
     */
    @PostMapping("PPT_reader_unallot_s")
    @ResponseBody
    public AjaxResult  PPT_reader_unallot_s(String status,Model model,String ids) {
        //稿件ids
        log.info("进来了==========================");
        log.info("ids====================={}",ids);
        String id=ids.substring(0,ids.length()-1);
        String[] idss=id.split(",");
        List<Long> draftid=new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }
        log.info("=====================>{}",ids);
        //分配人id
        SysUser sysUser = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        //被分配人id
        SysUser sysUser1 = draftService.getUserIdByUserName(status);

        for (int i = 0; i < draftid.size(); i++) {
            //更新稿件
            Draft draft = new Draft();
            draft.setId(draftid.get(i));
            draft.setStatusCode(StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION);//1031
            draft.setUpdateTime(LocalDateTime.now());
            draft.setLastOperator(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
            draftService.updateById(draft);
            //插入分配表
            Allot allot=new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION);//1031
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);
        }

        //操作日志
        for (int i = 0; i < draftid.size(); i++) {
            applicationEventPublisher.publishEvent(new DraftLog()
                    .setGroupId(draftService.getById(draftid.get(i)).getGroupId())
                    .setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setCreateTime(LocalDateTime.now())
                    .setUserId(Utility.getSysUser().getId())
                    .setDraftId(draftid.get(i))
                    .setPrimaryState(StatusPPTAudio.STATUS_PPT_FUNCTIONARY_DISTRIBUTION)
                    .setAfterState(StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION));
        }

        return toAjax(true);
    }
    /**
     *@author 孙祺至
     *@date 2019/12/12 20:49
     * 查看详情
     */
    @GetMapping("pptUnmakeBefore/{id}")
    public String pptUnmakeBefore(Model model,@PathVariable("id")Long id,String buttonFlag,String pptEditFlag
            ,String pptFlag,String checkFlag,String reasonFlag,String agreeFlag,String rejectFlag,String realseFlag,
                                  String pptdraft,String changeFlag){
        Draft draft = draftService.getById(id);
        model.addAttribute("draft",draft);
        model.addAttribute("pptEditFlag",pptEditFlag);
        model.addAttribute("checkFlag",checkFlag);
        model.addAttribute("reasonFlag",reasonFlag);
        model.addAttribute("agreeFlag",agreeFlag);
        model.addAttribute("rejectFlag",rejectFlag);
        model.addAttribute("pptdraft",pptdraft);
        model.addAttribute("buttonFlag",buttonFlag);
        model.addAttribute("realseFlag",realseFlag);
        model.addAttribute("pptFlag",pptFlag);
        model.addAttribute("changeFlag",changeFlag);
        Ppt ppt = pptService.getOne(new QueryWrapper<Ppt>().lambda().eq(Ppt::getDraftId,draft.getId()));
        model.addAttribute("ppt",ppt);
        if(ppt != null){
            showReason(model,ppt);
        }

        //操作日志
        applicationEventPublisher.publishEvent(new DraftLog()
                .setGroupId(draftService.getById(id).getGroupId())
                .setActionType(DraftLogConstant.ACTION_LOOK)
                .setCreateTime(LocalDateTime.now())
                .setUserId(Utility.getSysUser().getId())
                .setDraftId(id));
//                .setPrimaryState(StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION)
//                .setAfterState(StatusPPTAudio.STATUS_PPT_PPTTORECORD_UPLOADTO));

        return prefix+"look";
    }




    private void showReason(Model model,Ppt ppt){
        List<Check> checkList = checkService.list(new QueryWrapper<Check>().lambda()
                .eq(Check::getDraftId,ppt.getId())
                .eq(Check::getUserId,ppt.getLastOperator())
                .orderByDesc(Check::getCreateTime));
        String reason = null;
        if(!CollectionUtils.isEmpty(checkList)){
            reason = checkList.get(0).getReason();
        }
        model.addAttribute("reason",reason);
    }

    /**
     *@author 孙祺至
     *@date 2019/12/12 20:49
     * 查看详情
     */
    @GetMapping("pptUnmake/{id}")
    public String pptUnmake(Model model,@PathVariable("id")Long id){
        model.addAttribute("draft",draftService.getById(id));
        return prefix+"upload";
    }

    @PostMapping("pptRelease")
    @ResponseBody
    public AjaxResult pptRelease(Model model,Long id,Long audioId,String draftText,String draftTitle,Long draftNum,String fileName){
        log.info("drafttext==========="+draftText);
        log.info("drafttitle==========="+draftTitle);
        log.info("draftNum==========="+draftNum);

        Draft draft = new Draft();
        draft.setDraftTitle(draftTitle);
        draft.setDraftText(draftText);
        draft.setDraftNum(draftNum);
        draft.setFileName(fileName);
        draft.setId(id);
        draft.setStatusCode(StatusPPTAudio.STATUS_PPT_PPTTORECORD_UPLOADTO);//1032
       //操作记录
        if ( draftService.updateById(draft)){
            applicationEventPublisher.publishEvent(new DraftLog()
                    .setGroupId(draftService.getById(id).getGroupId())
                    .setActionType(DraftLogConstant.ACTION_EDIT)
                    .setActionContent("稿件更新成功")
                    .setCreateTime(LocalDateTime.now())
                    .setUserId(Utility.getSysUser().getId())
                    .setDraftId(id));
//                        .setPrimaryState(StatusPPTAudio.STATUS_PPT_PPTTORECORD_UPLOADTO)
//                        .setAfterState(StatusPPTAudio.STATUS_PPT_BUTTJOJINT_FAILED)););
        };
        //操作日志
        applicationEventPublisher.publishEvent(new DraftLog()
                .setGroupId(draftService.getById(id).getGroupId())
                .setActionType(DraftLogConstant.ACTION_OTHER)
                .setCreateTime(LocalDateTime.now())
                .setUserId(Utility.getSysUser().getId())
                .setDraftId(id)
                .setActionContent("发布PPT")
                .setPrimaryState(StatusPPTAudio.STATUS_PPT_BUTTJOJINT_DISTRIBUTION)
                .setAfterState(StatusPPTAudio.STATUS_PPT_PPTTORECORD_UPLOADTO));

        QueryWrapper<Ppt> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Ppt::getDraftId, id);
        Ppt ppt = pptService.getOne(queryWrapper);
        log.info("=============ppt为空？？？===="+ppt.getId());
        if(ppt != null){
            ppt.setDraftId(id);
            ppt.setStatusCode(StatusPPTAudio.STATUS_PPT_PPTTORECORD_UPLOADTO);//1032
            ppt.setUpdateTime(LocalDateTime.now());
            log.info("==========id====="+audioId);
            pptService.updateStatusByDraftId(ppt);
        }



        return success();
    }
    /**
     * @Author//宋昱
     * 音视频校对组长
     * 未分配的音频稿件列表
     **/
    private String prefixAudio = "admin/draft/";
    @RequestMapping("audioDraft")
    public String indexAudio(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftText())) {
            queryWrapper = queryWrapper.like("draft_text",draft.getDraftText());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftNum())) {
            queryWrapper = queryWrapper.like("draft_num",draft.getDraftNum());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftType())) {
            queryWrapper = queryWrapper.like("draft_type",draft.getDraftType());
        }
        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            queryWrapper = queryWrapper.like("submit_time",draft.getSubmitTime());
        }
        if(!ObjectUtils.isEmpty(draft.getUserId())) {
            queryWrapper = queryWrapper.like("user_id", draft.getUserId());
        }
        if(!ObjectUtils.isEmpty(draft.getStatusCode())) {
            queryWrapper = queryWrapper.like("status_code",draft.getStatusCode());
        }
        if(!ObjectUtils.isEmpty(draft.getIsDelete())) {
            queryWrapper = queryWrapper.like("is_delete",draft.getIsDelete());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            queryWrapper = queryWrapper.like("group_id",draft.getGroupId());
        }
        if(!ObjectUtils.isEmpty(draft.getLastOperator())) {
            queryWrapper = queryWrapper.like("last_operator",draft.getLastOperator());
        }
        if(!ObjectUtils.isEmpty(draft.getIsPass())) {
            queryWrapper = queryWrapper.like("is_pass",draft.getIsPass());
        }
        queryWrapper.lambda().eq(Draft::getDraftType, StatusConstant.DRAFT_TYPE__AUDIO);//3
        queryWrapper.lambda().eq(Draft::getStatusCode, StatusConstant.STATUS_DRAFT_AUDIO_UNALLOT);//1007
        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
        PageInfo info = new PageInfo(pageInfo);
        List<Draft> draftList = info.getList();
        for (Draft draft1 : draftList) {
            draft1.setWriterName(userService.selectByPrimaryKey(draft1.getUserId()).getUsername());
//            int length = draft1.getDraftText().length();
//            if (length > 10) {
//                draft1.setSubText(draft1.getDraftText().substring(0,10) + "...");
//            } else {
//                draft1.setSubText(draft1.getDraftText());
//            }
        }
        model.addAttribute("submitTimeSpace", submitTimeSpace);
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix + "draftunAllot";
    }
    /**
     * @Author 宋昱
     * @Description //TODO
     * @Date 2019/12/19 19:37
     * @Param
     * @return
     **/
    @GetMapping("assignmentAll")
    public String assignmentAll(Model model,String ids){
        SysUser sysUser = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Long> childrenId = draftService.getChildrenIdByParentId(sysUser.getId());
        Map<Integer,String> map = new HashMap<>();
        for (int j = 0; j < childrenId.size(); j++) {
            //======================肖
            SysUser children = userService.selectByPrimaryKey(childrenId.get(j));
            List<com.mbyte.easy.security.entity.SysRole> childrenRoles = children.getRoles();
            for (com.mbyte.easy.security.entity.SysRole childrenRole : childrenRoles) {
                if (SysRole.AUDIO_PROOFREADER.equals(childrenRole.getId())||SysRole.VIDEO_PROOFREADER.equals(childrenRole.getId())){
                    map.put(j,draftService.getUserNameByUserId(childrenId.get(j)).getUsername());
                }
            }
            //======================
        }
        model.addAttribute("username",map);
        model.addAttribute("ids",ids);
        return prefix + "draftMakeAllot";

//        //获取当前的登陆的用户名
//        String Username= Utility.getCurrentUsername();
//        //根据用户名获取校对组长id
//        Long userIdByUsernameAudio = draftService.getUserIdByUsernameAudio(Username);
//        model.addAttribute("userIdByUsernameAudio",userIdByUsernameAudio);
//        //根据用户名id获取被分配人的id
//        List<SysUser> list = new ArrayList<>();
//        List<Long> childrenId = draftService.getChildrenNameByChildrenIdAudio(userIdByUsernameAudio);
//        for(int i = 0; i < childrenId.size(); i++){
//            SysUser sysUser=new SysUser();
//            sysUser=userService.selectByPrimaryKey(childrenId.get(i));
//            list.add(sysUser);
//        }
//        model.addAttribute("list",list);
//        String draftId=ids;
//        String ID[]=draftId.split(",");
//        Long[] LongID = new Long[ID.length];
//        //把字符串数组转换为long类型数组
//        for(int i=0;i<ID.length;i++){
//            LongID[i] = Long.parseLong(ID[i]);
//        }
//        model.addAttribute("draftId",LongID);
//        model.addAttribute("draft",draftService.getById(3L));

    }

    /**
     * 刘雪奇
     * 音频校对组长
     * 未分配页面的分配按钮
     * 分配功能
     */
    @PostMapping("allotAudioDraft")
    @ResponseBody
    public AjaxResult allotAudio(String status, Model model, String ids, String name){
        name = Utility.getGroupName(name);
        if(groupService.existGroupName(name)){
            return AjaxResult.error("组名【"+name+"】今日已存在！");
        }
          //音频稿件的ids
        String id = ids.substring(0,ids.length() - 1);
        String[] idss = id.split(",");
        List<Long> draftid = new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }
        SysUser sysUser = draftService.getUserIdByUserNameAudio(Utility.getCurrentUsername());
        SysUser sysUser1 = draftService.getUserIdByUserNameAudio(status);
        String UUid = Utility.getUUID();
        for (int i = 0; i < draftid.size(); i++) {
            //更新
            Draft draft = new Draft();
            draft.setId(draftid.get(i));
            draft.setStatusCode(STATUS_DRAFT_AUDIO_ALLOT);//1008
            draft.setGroupId(UUid);
            draft.setLastOperator(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
            draftService.updateById(draft);
            //插入分配表
            Allot allot = new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(STATUS_DRAFT_AUDIO_ALLOT);//1008
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);
        }
        Group group = new Group();

        group.setGroupId(UUid);
        group.setName(name);
        group.setUserId(sysUser1.getId());
        draftService.insertToGroup(group);

        for (int i = 0; i < draftid.size(); i++) {
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setDraftId(draftid.get(i))
                    .setGroupId(UUid)
                    .setPrimaryState(STATUS_DRAFT_AUDIO_UNALLOT)
                    .setAfterState(STATUS_DRAFT_AUDIO_ALLOT));
        }
        return AjaxResult.success();

//        String groupid = Utility.getUUID();
//        Group group = new Group();
//        group.setGroupId(groupid);
//        group.setUserId(allot.getAllotnoId());
//        groupService.save(group);
//        for(int i = 0; i < longID.length; i++){
//            Draft draft = new Draft();
//            draft.setId(longID[i]);
//            draft.setStatusCode(STATUS_DRAFT_AUDIO_ALLOT);
//            draft.setLastOperator(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
//            draft.setGroupId(groupid);
//            draftService.updateById(draft);
//            allot.setDraftId(longID[i]);
//            allot.setStatusCode(STATUS_DRAFT_AUDIO_ALLOT);
//            allotService.save(allot);
//        }

//        return this.success();
    }
    /**
     * @Author//宋昱
     * 音视频校对组长
     * 已分配的稿件列表
     **/
    @RequestMapping("audioDraftAllotList")
    public String audioDraftAllot(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftText())) {
            queryWrapper = queryWrapper.like("draft_text",draft.getDraftText());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftNum())) {
            queryWrapper = queryWrapper.like("draft_num",draft.getDraftNum());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftType())) {
            queryWrapper = queryWrapper.like("draft_type",draft.getDraftType());
        }
        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            queryWrapper = queryWrapper.like("submit_time",draft.getSubmitTime());
        }
        if(!ObjectUtils.isEmpty(draft.getUserId())) {
            queryWrapper = queryWrapper.like("user_id",draft.getUserId());
        }
        if(!ObjectUtils.isEmpty(draft.getStatusCode())) {
            queryWrapper = queryWrapper.like("status_code",draft.getStatusCode());
        }
        if(!ObjectUtils.isEmpty(draft.getIsDelete())) {
            queryWrapper = queryWrapper.like("is_delete",draft.getIsDelete());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            queryWrapper = queryWrapper.like("group_id",draft.getGroupId());
        }
        if(!ObjectUtils.isEmpty(draft.getLastOperator())) {
            queryWrapper = queryWrapper.like("last_operator",draft.getLastOperator());
        }
        if(!ObjectUtils.isEmpty(draft.getIsPass())) {
            queryWrapper = queryWrapper.like("is_pass",draft.getIsPass());
        }
        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        String userName = Utility.getCurrentUsername();
        SysUser userIdByUserName = draftService.getUserIdByUserName(userName);
        List<Allot> draftByUserId = draftService.getDraftByUserId(userIdByUserName.getId());
        if (draftByUserId.size() != 0) {
            queryWrapper.in("td.id", draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.lambda().eq(Draft::getDraftType, StatusConstant.DRAFT_TYPE__AUDIO);//类型3
            queryWrapper.eq("td.status_code", STATUS_DRAFT_AUDIO_ALLOT);//1008

            IPage<Draft> pageInfo = draftService.pageList(page, queryWrapper);
            PageInfo info = new PageInfo(pageInfo);

            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioDraftAllotList";
        } else {
            queryWrapper.lambda().eq(Draft::getDraftType,StatusWriter.ERROR);
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioDraftAllotList";
        }


    }
    /**
     * @Author//宋昱
     * 音频校对人
     * 未分配的音频稿件
     **/
    @RequestMapping("audioDraftPeopleList")
    public String audioDraftPeople(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }

        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        SysUser userIdByUserName = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Allot> draftByUserId = draftService.getDraftByAllotnoId(userIdByUserName.getId());
        if (draftByUserId.size() != 0) {
            queryWrapper.in("td.id", draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.lambda().eq(Draft::getDraftType, DRAFT_TYPE__AUDIO);
            queryWrapper.eq("td.status_code", StatusConstant.STATUS_DRAFT_AUDIO_ALLOT);//1008
            IPage<Draft> pageInfo = draftService.pageList(page, queryWrapper);

            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioDraftPeopleList";
        } else {
            queryWrapper.lambda().eq(Draft::getDraftType,StatusWriter.ERROR);
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioDraftPeopleList";
        }
    }

    /**
     * 刘雪奇
     * 音频校对人
     * 分配音频稿件
     * 分配功能
     */
    @GetMapping("assignmentAllPeople")
    public String assignmentAllPeople(Model model,String ids,Allot allot){
        String username = Utility.getCurrentUsername();
        SysUser sysUser = draftService.getUserIdByUserNameAudio(username);
        List<Long> childrenId = draftService.getChildrenNameByChildrenIdAudio(sysUser.getId());
        Map<Integer,String> map = new HashMap<>();
        for (int i = 0; i < childrenId.size(); i++) {
            SysUser children = userService.selectByPrimaryKey(childrenId.get(i));
            List<com.mbyte.easy.security.entity.SysRole> childrenRoles = children.getRoles();
            for (com.mbyte.easy.security.entity.SysRole childrenRole : childrenRoles) {
                log.info("=============="+sysUser.getRoles().get(0).getId());
                if(sysUser.getRoles().get(0).getId().equals(SysRole.AUDIO_PROOFREADER)) {
                    if (SysRole.AUDIO_PRODUCER.equals(childrenRole.getId())) {
                        map.put(i, draftService.getUserNameByUserId(childrenId.get(i)).getUsername());
                    }
                }else if(sysUser.getRoles().get(0).getId().equals(SysRole.VIDEO_PROOFREADER)){
                    if (SysRole.DRAFT_VISUAL_PRODUCER.equals(childrenRole.getId())){
                        map.put(i,draftService.getUserNameByUserId(childrenId.get(i)).getUsername());
                    }
                }
            }
        }
        model.addAttribute("username",map);
        model.addAttribute("ids",ids);

        return prefix+"draftMakeAllotPeople";

    }

    /**
     * 刘雪奇
     * 音频校对人
     * 分配音频稿件
     */
    @PostMapping("allotAudioDraftPeople")
    @ResponseBody
    public AjaxResult allotAudioDraftPeople( String status, String ids){
        //稿件ids
        String id = ids.substring(0,ids.length() - 1);
        String[] idss = id.split(",");
        List<Long> draftid = new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }

        //分配人id
        String username = Utility.getCurrentUsername();
        SysUser sysUser = draftService.getUserIdByUserNameAudio(username);
        //被分配人id
        SysUser sysUser1 = draftService.getUserIdByUserNameAudio(status);

        for (int i = 0; i < draftid.size(); i++) {
            //更新稿件
            Draft draft = new Draft();
            draft.setId(draftid.get(i));
            draft.setStatusCode(STATUS_AUDIO_ALLOTED_PEOPLE);//1009
            draft.setLastOperator(draftService.getUserIdByUserNameAudio(Utility.getCurrentUsername()).getId());
            draftService.updateById(draft);
            //插入分配表
            Allot allot = new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setStatusCode(STATUS_AUDIO_ALLOTED_PEOPLE);//1009
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);
        }
        for(int i=0;i<draftid.size(); i++) {
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setDraftId(draftid.get(i)).setGroupId(draftService.getById(draftid.get(i)).getGroupId())
                    .setAfterState(STATUS_DRAFT_AUDIO_ALLOT).setPrimaryState(STATUS_AUDIO_ALLOTED_PEOPLE));
        }
        return toAjax(true);

    }
    /**
    * @Author//宋昱
     * @Description //音频校对人已分配的音频稿件
     * @Date 2019/12/16 15:47
            **/
    @RequestMapping("audioDraftAllotPeopleList")
    public String audioDraftAllotPeopleList(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft,String name) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }

        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        SysUser userIdByUserName = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Allot> draftByUserId = draftService.getDraftByUserId(userIdByUserName.getId());
        Map<Long,String> map = new HashMap<>();
        if (draftByUserId.size() != 0) {
            queryWrapper.in("td.id", draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.lambda().eq(Draft::getDraftType, DRAFT_TYPE__AUDIO);
            queryWrapper.eq("td.status_code", STATUS_AUDIO_ALLOTED_PEOPLE);//1009
            IPage<Draft> pageInfo = draftService.pageList(page, queryWrapper);

            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo",draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioDraftAllotPeopleList";
        } else {
            queryWrapper.lambda().eq(Draft::getDraftType,StatusWriter.ERROR);
            IPage<Draft> pageInfo = draftService.pageList(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo",draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioDraftAllotPeopleList";
        }

//        String Username= Utility.getCurrentUsername();
//        //获取当前的登陆的用户名
//
//        //根据用户名获取校对人id
//        Long userIdByUsernameAudio= draftService.getUserIdByUsernameAudio(Username);
//        //根据校对人id在Allot表中获取draft的id
//
//        List<Long> list2=draftService.selectDraftIdByAllotId(userIdByUsernameAudio);
//        if(list2 != null) {
//            queryWrapper.lambda().eq(Draft::getDraftType, StatusConstant.DRAFT_TYPE__AUDIO);
//            queryWrapper.lambda().eq(Draft::getStatusCode, StatusConstant.STATUS_AUDIO_ALLOTED_PEOPLE);
//            queryWrapper.in("id", list2);
//        }
//        IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
//        model.addAttribute("submitTimeSpace", submitTimeSpace);
//        model.addAttribute("searchInfo", draft);
//        model.addAttribute("pageInfo", new PageInfo(pageInfo));
//        return prefix + "audioDraftAllotPeopleList";
    }
    /**
    * @Author//宋昱
    * @Description //音频制作人未制作音频的界面
     * @Date 2019/12/19 11:29
     **/
    @RequestMapping("audioMakeBefore")
    public String audioMakeBefore(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }

        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        SysUser userIdByUserName = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Allot> draftByUserId = draftService.getDraftByAllotnoId(userIdByUserName.getId());
        if (draftByUserId.size() != 0) {
            queryWrapper.in("td.id", draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.lambda().eq(Draft::getDraftType, DRAFT_TYPE__AUDIO);
            queryWrapper.eq("td.status_code", STATUS_AUDIO_ALLOTED_PEOPLE);//1009
            IPage<Draft> pageInfo = draftService.pageList(page, queryWrapper);

            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioMakeBeforeList";
        } else {
            queryWrapper.lambda().eq(Draft::getDraftType, StatusWriter.ERROR);
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);

            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "audioMakeBeforeList";
        }
    }

    /**
     * 刘雪奇
     * 查看详情
     */
    @GetMapping("audioUnmakeBefore/{id}")
    public String audioUnmakeBefore(Model model,@PathVariable("id")Long id){
        model.addAttribute("draft",draftService.getById(id));
        return prefix+"look";
    }

    /**
     * 刘雪奇
     * 音频录制人
     * 查看原稿件
     */
    @GetMapping("unMakeAudioBefore/{id}")
    public String unMakeAudioBefore(Model model, @PathVariable("id") Long id
            ,String realseFlag,String buttonFlag,String checkFlag,String reasonFlag,String agreeFlag,
                                    String rejectFlag,String upFlag,String downFlag,String noFlag,String updateFlag) {
        Draft draft = draftService.getById(id);
        model.addAttribute("draft",draft );
        QueryWrapper<Audio> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Audio::getDraftId, id);
        Audio audio = audioService.getOne(queryWrapper);
        if (audio != null) {
            model.addAttribute("audioUrl", audio.getAudioUrl());
            model.addAttribute("audio", audio);
            showReason(model,audio);
        }

        model.addAttribute("updateFlag",updateFlag);
        model.addAttribute("realseFlag",realseFlag);
        model.addAttribute("agreeFlag",agreeFlag);
        model.addAttribute("rejectFlag",rejectFlag);
        model.addAttribute("buttonFlag",buttonFlag);
        model.addAttribute("checkFlag",checkFlag);
        model.addAttribute("reasonFlag",reasonFlag);
        model.addAttribute("downFlag",downFlag);
        model.addAttribute("upFlag",upFlag);
        model.addAttribute("noFlag",noFlag);
        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_LOOK)
                .setDraftId(id));

        return prefix + "aMakerLook";
    }
    private void showReason(Model model,Audio audio){
        List<Check> checkList = checkService.list(new QueryWrapper<Check>().lambda()
                .eq(Check::getDraftId,audio.getDraftId())
                .eq(Check::getUserId,audio.getLastOperator())
                .orderByDesc(Check::getCreateTime));
        log.info("reason是"+checkList);
        String reason = null;
        LocalDateTime reasonTime = null;
        if(!CollectionUtils.isEmpty(checkList)){
            reason = checkList.get(0).getReason();
            reasonTime = checkList.get(0).getUpdateTime();
        }
        model.addAttribute("reasonTime",reasonTime);
        model.addAttribute("reason",reason);
    }


    /**
     * @Author//牛英健
     * @Description //稿件转视制作人未制作音频的界面
     * @Date 2019/12/19 11:29
     **/
    @RequestMapping("videoMakeBefore")
    public String videoMakeBefore(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String createTimeSpace, String updateTimeSpace, Draft draft) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<Draft>();
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            queryWrapper = queryWrapper.like("draft_title",draft.getDraftTitle());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftText())) {
            queryWrapper = queryWrapper.like("draft_text",draft.getDraftText());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftNum())) {
            queryWrapper = queryWrapper.like("draft_num",draft.getDraftNum());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftType())) {
            queryWrapper = queryWrapper.like("draft_type",draft.getDraftType());
        }
        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            queryWrapper = queryWrapper.like("submit_time",draft.getSubmitTime());
        }
        if(!ObjectUtils.isEmpty(draft.getUserId())) {
            queryWrapper = queryWrapper.like("user_id",draft.getUserId());
        }
        if(!ObjectUtils.isEmpty(draft.getStatusCode())) {
            queryWrapper = queryWrapper.like("status_code",draft.getStatusCode());
        }
        if(!ObjectUtils.isEmpty(draft.getIsDelete())) {
            queryWrapper = queryWrapper.like("is_delete",draft.getIsDelete());
        }
        if(!ObjectUtils.isEmpty(draft.getGroupId())) {
            queryWrapper = queryWrapper.like("group_id",draft.getGroupId());
        }
        if(!ObjectUtils.isEmpty(draft.getLastOperator())) {
            queryWrapper = queryWrapper.like("last_operator",draft.getLastOperator());
        }
        if(!ObjectUtils.isEmpty(draft.getIsPass())) {
            queryWrapper = queryWrapper.like("is_pass",draft.getIsPass());
        }
        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        SysUser userIdByUserName = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        List<Allot> draftByUserId = draftService.getDraftByAllotnoId(userIdByUserName.getId());
        if (draftByUserId.size() != 0) {
            queryWrapper.in("td.id", draftByUserId.stream().map(Allot::getDraftId).collect(Collectors.toList()));
            queryWrapper.lambda().eq(Draft::getDraftType, DRAFT_TYPE__AUDIO);
            queryWrapper.eq("td.status_code", STATUS_AUDIO_ALLOTED_PEOPLE);//1009

            IPage<Draft> pageInfo = draftService.pageList(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "video/videoMakeBeforeList";
        } else {
            queryWrapper.lambda().eq(Draft::getDraftType, StatusWriter.ERROR);
            IPage<Draft> pageInfo = draftService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix + "video/videoMakeBeforeList";
        }
    }

    /**
     * 七队视频  新建视频
     */
    @RequestMapping("sevenVideo")
    public String sevenVideo(Model model){
        model.addAttribute("id",0);
        return prefix+"sevenVideo/add";
    }

    /**
     * @Author 牛英健
     * @Description 上传
     * @Date 2019/12/19 20:52
     * @Param file 文件
     * @return
     **/
    @PostMapping("uploadAudioVideo")
    @ResponseBody
    public AjaxResult uploadAudioVideo(@RequestParam("file") MultipartFile file) {
        if (file != null) {
            log.info("====================");
            String url = OssFileUtils.uploadSingleFile(file);
            log.info("url--> {}",url);
           
            return AjaxResult.success(url);
        }
        return AjaxResult.error();
    }

    /**
    *七队视频 发布
     */
    @PostMapping("reales")
    @ResponseBody
    public AjaxResult realse(@RequestParam("draftTitle") String draftTitle,@RequestParam("fileName") String fileName,
                             @RequestParam("draftText") String draftText){
        Draft draft = new Draft();
        draft.setDraftTitle(draftTitle);
        draft.setDraftText(draftText);
        draft.setFileName(fileName);
        draft.setSubmitTime(LocalDateTime.now());
        draft.setCreateTime(LocalDateTime.now());
        draft.setUpdateTime(LocalDateTime.now());
        draft.setDraftType(DraftType.SVIDEO);
        draft.setUserId(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
        draft.setLastOperator(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
        draft.setStatusCode(StateDic.Submit);
        draft.setIsPass(DraftIsPass.NotCheck);
        draft.setIsDelete(DraftIsPass.NotDelete);
        draftService.insert2Id(draft);
        log.info("save后---->{}",draft.getId());
        //操作日志
        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ADD)
                .setDraftId(draft.getId()));
        return AjaxResult.success(true);
    }


}

